App.controller('customerController', ['$rootScope', '$scope', '$state', 'Page', function ($rootScope, $scope, $state, Page) {

	//$scope.testObj = [
	//	{
	//		name : 'title1',
	//		value : 'value1'
	//	},
	//	{
	//		name : 'title2',
	//		value : 'value2'
	//	},
	//	{
	//		name : 'title3',
	//		value : 'value3'
	//	},
	//	{
	//		name : 'title4',
	//		value : 'value4'
	//	}
	//];
	//$scope.clickToggle = function(event,$index) {
	//	var toggleDiv = $(event.currentTarget).parent().parent().next("div");
	//	if(toggleDiv.hasClass("panel-collapse in")) {
	//		toggleDiv.removeClass("in");
	//		toggleDiv.addClass("collapse");
	//	} else {
	//		toggleDiv.removeClass("collapse");
	//		toggleDiv.addClass("in");
	//	}
    //
	//	$("#accordion2").find("div.panel.panel-default").each(function(index,data){
	//		if(index != $index) {
	//			var opt = $(data).find("div.panel-collapse");
	//			if(opt.hasClass("panel-collapse in")) {
	//				opt.removeClass("in");
	//				opt.addClass("collapse");
	//			}
	//		}
	//	})
	//};

	$scope.scheduleQuery = {};
    $scope.customerGrid = {
    	options : {
    		lazy : true
    	},
        column_defs: [
			{
			    target: 1,
			    template: function(row) {
					 //return '<a ed-click="viewCustomerRes" title="查看客户资源信息">'+row.customerName+'</a>';
					 return row.customerName;
			   }
			 },
            {
                target: 6,
                buttons: [
                    {
                        name: '编辑',
                        clazz: 'btn-edit',
                        icon: 'fa-edit',
                        event: function(row){
                    		$scope.customer = row;
            				$scope.customerAddModal.show();
                        },
                        visiable: function(row) {
                            return row.status == '1';
                        }
                    },
                    {
                        name: '失效',
                        clazz: 'btn btn-delete',
                        icon: 'fa-trash-o',
                        event: function(row){
                    		Page.confirm("失效后客户信息将不可用，确定继续操作?", function () {
				                Page.ajaxPost('customer/delete.do', row, function () {
				                    $scope.customerGrid.query();
				                });
				            });
                        },
                        visiable: function(row) {
                            return row.status == '1';
                        }
                    },
                    {
                        name: '设置账号',
                        clazz: 'btn btn-success',
                        icon: 'fa fa-cog',
                        event: function(row){
                    		 $scope.customerUserModal.open(row);
                        },
                        visiable: function(row) {
                            return row.status == '1';
                        }
                    },
                    {
                        name: '查看',
                        clazz: 'btn green',
                        icon: 'fa-search',
                        event: function(row){
                    		$scope.customerId = row.customerId;
				            $scope.showResoModal = true;
				            $scope.customerContractModal.show();
                        },
                        visiable: function(row) {
                            return false;
                        }
                    }
                ]
            }
        ],
        add : function() {
            $scope.customer = {};
            $scope.customerAddFlag = true;
            $scope.customerAddModal.show();
        },
        viewCustomerRes : function(row){
        	 $scope.customerName = row.customerName;
        	 $scope.customerId = row.customerId;
        	 var param = {};
        	 param.customerId = row.customerId;
        	 Page.ajaxPost('customer/getContracts4Customer.do', param, function (resp) {
    			 $scope.contracts = resp.data.contracts;
    			 $scope.customerResourceScheduleModal.reset();
    			 $scope.customerResourceScheduleModal.query();
    			 $scope.customerResourceScheduleModal.show();
        		});
        	
        }
    };
    
    $scope.$on('$viewContentLoaded', function() {
        $scope.customerGrid.query.status = "1";
        $scope.customerGrid.query();
    });
    
    $scope.customerAddModal = {
    	onShow : function(){
			$scope.customer.bLFile = {
				path: $scope.customer.businessLicenseImg
			};
			$scope.customer.oCFile = {
				path: $scope.customer.orgCertificateImg
			};
			$scope.customer.tCFile = {
				path: $scope.customer.taxCertificateImg
			};
			if($scope.customer.bLFile.path != ''){
				$("#customerAddModalBLImgViewArea").attr("src",$rootScope.nginxPath + $scope.customer.bLFile.path);
			}
			if($scope.customer.bLFile.path != ''){
				$("#customerAddModalOCImgViewArea").attr("src",$rootScope.nginxPath + $scope.customer.oCFile.path);
			}
			if($scope.customer.bLFile.path != ''){
				$("#customerAddModalTCImgViewArea").attr("src",$rootScope.nginxPath + $scope.customer.tCFile.path);
			}
			
			this.watchBFile = $scope.$watch('customer.bLFile', function (newValue, oldValue, $scope) {
				if (oldValue == undefined || newValue == undefined || newValue.path == undefined) {
				            return;
				}
				$scope.customer.businessLicenseImg = newValue.path;
				$("#customerAddModalBLImgViewArea").attr("src",$rootScope.nginxPath + $scope.customer.businessLicenseImg);
			});
		    
		    this.watchOFile = $scope.$watch('customer.oCFile', function (newValue, oldValue, $scope) {
				if (oldValue == undefined || newValue == undefined || newValue.path == undefined) {
				            return;
				}
				$scope.customer.orgCertificateImg = newValue.path;
				$("#customerAddModalOCImgViewArea").attr("src",$rootScope.nginxPath + $scope.customer.orgCertificateImg);
			});
		    
		    this.watchTFile = $scope.$watch('customer.tCFile', function (newValue, oldValue, $scope) {
				if (oldValue == undefined || newValue == undefined || newValue.path == undefined) {
				            return;
				}
				$scope.customer.taxCertificateImg = newValue.path;
				$("#customerAddModalTCImgViewArea").attr("src",$rootScope.nginxPath + $scope.customer.taxCertificateImg);
			});
		},
		onOkClick : function() {
	    	if(!$scope.validateForm.$valid) {
	            $scope.validateForm.doValidate();
	        } else {
	            if(!$scope.customer.customerId) { //添加
	                Page.ajaxPost('customer/add.do', $scope.customer, function (resp) {
	                    $scope.customerGrid.query();
	                    $scope.gridAddFlag = false;
	                    $scope.customerAddModal.hide();
	                    $scope.customerAddModal.watchBFile();
	                    $scope.customerAddModal.watchOFile();
	                    $scope.customerAddModal.watchTFile();
	                });
	            } else {
	                Page.ajaxPost('customer/update.do', $scope.customer, function (resp) {
	                    $scope.customerGrid.query();
	                    $scope.customerAddModal.hide();
	                    $scope.customerAddModal.watchBFile();
	                    $scope.customerAddModal.watchOFile();
	                    $scope.customerAddModal.watchTFile();
	                });
	            }
	        }
    	},
    	onHidden : function() {
        	$scope.validateForm.reset();
        	this.watchBFile();
	        this.watchOFile();
	        this.watchTFile();
    	}
    };

    $scope.resourceGrid = {
        column_defs: [
            {
                target: 1,
                template: function(row) {
                    return '<a ed-click="showContractRes">'+row.contractNo+'</a>'
                }
            }
        ],

        add : function() {
            $scope.resourceAddModal.show();
        },
        showContractRes : function(row) {
            $scope.showResDetailsModal = true;
            $scope.contractId = row.contractId;
            $scope.resourceDetailsModal.show();
            $scope.resourceDetailsGrid.query();
        }
    };

    $scope.resourceDetailsGrid = {
//    		options: {
//    	        lazy: true// 是否延迟加载，这个属性是自定义属性，jQuery Datatables本身没有
//    	    }
    };


    //客户资源排期明细
    $scope.customerResourceScheduleModal = {
    		onShow : function(){
				this.setTitle('客户资源-- ' + $scope.customerName);
			},
			query : function(month,lastOrNext, monthOrYear) {
				var param = {};
				param.month = month;// 当前月份
				param.lastOrNext = lastOrNext;// -1：上一月 上一年 1：下一月 下一年
				param.monthOrYear = monthOrYear;// 1:年 2：月
				param.pageIndex = 0;
				param.pageSize = 15;			 
				param.resourceParentType = $scope.scheduleQuery.resourceParentType;//父类型
				param.resourceType = $scope.scheduleQuery.resourceType;//父类型
				param.contractId = $scope.scheduleQuery.contractId;//合同id
				param.customerId = $scope.customerId;
				Page.ajaxPost('customer/findCustomerResSchedule.do', param, function(resp) {
					$scope.months = resp.data.months;
					$scope.days = resp.data.daysArray;
					$scope.dataArray = resp.data.dataArray;
					$scope.monthSelect = "";
					$scope.monthSelect = resp.data.currentMonth;
					$scope.lastYear = resp.data.lastYear;
					$scope.nextYear = resp.data.nextYear;
					$scope.totalPages = resp.data.totalPages;
					$scope.currentMonth = resp.data.currentMonth;
					// 调用分页
					laypage({
						cont : 'page_bar',
						pages : $scope.totalPages,// 得到总页数
						skin : '#12bdce',
						skip : true, // 是否开启跳页
						prev : '<', // 若不显示，设置false即可
						next : '>', // 若不显示，设置false即可
						groups : 5, //连续分页数
						curr: 1, //初始化当前页
						jump : function(obj,first) {// 触发分页后的回调
							/*obj是一个object类型。包括了分页的所有配置信息。
							 first一个Boolean类，检测页面是否初始加载。非常有用，可避免无限刷新。*/
							if(!first){
								//var param = {};
								param.month = $scope.currentMonth;// 当前月份
								param.pageIndex = obj.curr - 1;
								param.pageSize = 20;
									Page.ajaxPost('customer/findCustomerResSchedule.do', param, function(resp) {
										$scope.months = resp.data.months;
										$scope.days = resp.data.daysArray;
										$scope.dataArray = resp.data.dataArray;
										$scope.monthSelect = resp.data.currentMonth;
										$scope.lastYear = resp.data.lastYear;
										$scope.nextYear = resp.data.nextYear;
										$scope.totalPages = resp.data.totalPages;
										$scope.currentMonth = resp.data.currentMonth;
									});
							}
						}
					})
				});
			},
			
			
		  //选择月份
			monthChange : function(month) {
				this.query(month);
			},
			//选择资源类型
			parentTypeChange : function() {
				var param = {};
				var parentId = $scope.scheduleQuery.resourceParentType;
				if(parentId==''){
					$scope.resourceTypes=[];
				}else {
					param.parentId = parentId;
					Page.ajaxPost('mediaType/getMediaTypesByParentId.do', param, function(resp) {
						$scope.scheduleQuery.resourceType="";
						$scope.resourceTypes=resp.data;
					});
				}
			},
			reset : function(){
				$scope.scheduleQuery.resourceType="";
				$scope.scheduleQuery.resourceParentType="";
				$scope.scheduleQuery.contractId="";
			}
    };


    //查看资源确定
    customerContractTrue = function() {

    };
    //查看资源取消
    customerContractCancel = function() {
        $scope.customerContractModal.hide();
    };

    //新增资源确定
    resourceAddTrue = function() {
        if(!$scope.resourceValidate.$valid) {
            $scope.resourceValidate.doValidate();
        } else {
            $scope.resourceAddModal.hide();
        }
    };
    //新增资源取消
    resourceAddCancel = function() {
        $scope.resourceValidate.reset();
    };


    //合同明细确定按钮
    resourceDetailsTrue = function() {

    };

    //合同明细取消按钮
    resourceDetailsCancel = function() {
        $scope.resourceDetailsModal.hide();
    };
    
    $scope.customerUserModal = {
    	open : function(customer){
    		this.customer = customer;
    		this.user = {},
    		this.show();
    	},
    	onShow : function(){
    		Page.ajaxPostQuiet('customer/' + this.customer.customerId + '/user.do', null, function(resp) {
				$scope.customerUserModal.user = resp.data;
			});
    	},
    	passwordReset : function(){
    		Page.ajaxPostQuiet('customer/resetPassword.do', this.user, function (resp) {
				    Page.notice("密码得置成功!");
			});
    	},
    	onOkClick : function(){
    		$scope.customerUserForm.doValidate();
	       	if($scope.customerUserForm.$valid) {
				Page.ajaxPostQuiet('customer/' + this.customer.customerId + '/userSetting.do', this.user, function (resp) {
				    Page.notice("账号设置成功!");
				    $scope.customerUserModal.hide();
				    $scope.customerGrid.query()
				});
	        }
    	},
    	onHidden : function() {
    		$scope.customerUserForm.reset();
    	}
    }

}]);
